<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">疗养员</label>
        <el-input v-model="query.pilotId" clearable placeholder="疗养员" style="width: 185px;" class="filter-item"
          @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <el-dialog :close-on-click-modal="false" :before-close="hanldeMenuDialogClose" :visible="isMenuVisible"
        title="选择训练项目" width="500px">
        <el-button v-for="(item, index) in (crud.data[curRowIndex] && crud.data[curRowIndex].items)" :key="item.id" type="primary"
          plain style="display: block;margin-top:10px;width: 100%;" @click="hanldeItemClick(item.id)">
          {{ itemNames.get(item.id) }}
        </el-button>
      </el-dialog>

      <component v-if="dialogType" :is="dialogType" :key="dialogType" :trainId="curId" :itemId="curItemId" :pilot="curPilot"
        @cancel="handleDialogCancel" @close="handleDialogClose" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
        :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="疗养员" prop="pilotId">
            <el-select v-model="form.pilotId" style="width: 178px" placeholder="请选择" @change="changePilot">
              <el-option v-for="item in pilots" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="机器" prop="planeId">
            <el-select v-model="form.planeId" style="width: 178px" placeholder="请选择" @change="changePlane">
              <el-option v-for="item in planes" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="训练项目" prop="items">
            <el-select v-model="itemDatas" style="width: 370px" placeholder="请选择" multiple @remove-tag="removeTag"
              @change="changeItem">
              <el-option v-for="item in items" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="训练日期" prop="date">
            <el-date-picker v-model="form.date" type="date" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
        @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="pilot.name" label="疗养员" />
        <el-table-column prop="plane.name" label="机型" />
        <el-table-column label="训练结果">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="isPending(scope.row)">待训练</el-tag>
            <el-tag type="success" v-else-if="isPass(scope.row)">合格</el-tag>
            <el-tag type="danger" v-else>不合格</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="训练日期" :formatter="formatDate" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column v-if="checkPer(['admin', 'item:list'])" label="操作" style="display: inline-block;"
          width="200px" align="center">
          <template slot-scope="scope">
            <udOperation style="display: inline-block;" :data="scope.row" :permission="permission" />
            <el-button size="mini" type="primary" @click.stop="showDialog(scope.row, scope.$index)">进入训练</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudTrain from '@/api/train'
import { getPilotList } from '@/api/trainPilot'
import { getPlaneList } from '@/api/trainPlane'
import { getItemList } from '@/api/trainItem'

import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import LxjkzDialog from '../lxjkz/dialog.vue'
import KhzyhxDialog from '../khzy/dialog.vue'
import HpkhdzDialog from '../hpkhdz/dialog.vue'
import SxcjmnDialog from '../sxcjmn/dialog.vue'
import QtcjmnDialog from '../qtcjmn/dialog.vue'
import QtgnwdxDialog from '../qtgnwdx/dialog.vue'
import FxybdxDialog from '../fxybdx/dialog.vue'
import SwglqtgnDialog from '../swglqtgn/dialog.vue'
import DycxsjyDialog from '../dycxsjy/dialog.vue'
import Dycgksldialog from '../dycgksl/dialog.vue'
import DmjyhxDialog from '../dmjyhx/dialog.vue'
import QytyDialog from '../qyty/dialog.vue'
import TsljDialog from '../tslj/dialog.vue'

import { DIALOG_TYPES } from '@/utils/constants'
import { mapGetters } from 'vuex'

let trainItems = [];
const defaultForm = { id: null, pilotId: null, items: [], planeId: null, result: null, date: null, createBy: null, updateBy: null, pilot: null }
export default {
  name: 'Train',
  components: {
    pagination, crudOperation, rrOperation, udOperation,
    LxjkzDialog, KhzyhxDialog, HpkhdzDialog, SxcjmnDialog, QtcjmnDialog, QtgnwdxDialog,
    FxybdxDialog, SwglqtgnDialog, DycxsjyDialog, Dycgksldialog, DmjyhxDialog, QytyDialog,
    TsljDialog
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '档案', url: 'api/train', idField: 'id', sort: 'id,desc', crudMethod: { ...crudTrain } })
  },
  data() {
    return {
      pilotId: null,
      planeId: null,
      pilots: [],
      planes: [],
      isMenuVisible: false,
      dialogTitle: '训练项目',
      items: [],
      itemDatas: [],
      curRowIndex: 0,
      curId: -1,
      curItemId: -1,
      itemIndex: -1,
      dialogType: '',
      permission: {
        add: ['admin', 'train:add'],
        edit: ['admin', 'train:edit'],
        del: ['admin', 'train:del']
      },
      rules: {
        pilotId: [
          { required: true, message: '疗养员不能为空', trigger: 'blur' }
        ],
        planeId: [
          { required: true, message: '机型不能为空', trigger: 'blur' }
        ],
        items: [
          { required: true, message: '训练项目不能为空', trigger: 'blur' }
        ],
        'date': [
          { required: true, message: '训练日期不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'pilotId', display_name: '疗养员' }
      ],
      curPilot: null
    }
  },
  computed: {
    ...mapGetters([
      'itemNames'
    ]),
    isFinal() {
      if (this.curRowIndex == -1) {
        return false;
      }
      return (this.crud.data[this.curRowIndex].items.length - 1) == this.itemIndex
    }
  },
  created() {
    this.getItems()
  },
  methods: {
    isPending(row) {
      // 检查是否所有项目都没有 result
      if (!row || !row.items || row.items.length === 0) {
        return true
      }
      
      // 如果所有项目的 result 都为空、null、undefined，则返回 true
      return row.items.every(item => !item.result || item.result === '' || item.result === null || item.result === undefined)
    },
    
    isPass(row) {
      // 检查是否所有项目的 result 都为 "1"
      if (!row || !row.items || row.items.length === 0) {
        return false
      }
      
      // 如果所有项目的 result 都为 "1"，则返回 true
      return row.items.every(item => item.result === "1" || item.result === 1)
    },
    formatDate(row, column, cellValue, index) {
      const date = new Date(cellValue)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      // 使用toISOString().split('T')[0] 或者其他日期格式化方法来获取日期部分
      // 这里我们使用Intl.DateTimeFormat，它提供了更强大的国际化日期和时间格式化功能
      // return new Intl.DateTimeFormat('zh-CN').format(date);
      // 注意：Intl.DateTimeFormat('zh-CN')会返回类似'2023/4/1'的格式，这取决于用户的系统环境
    },
    changePilot(value) {
      this.form.pilotId = value;
      this.pilots.forEach(element => {
        if (element.id === value) {
          this.curPilot = element;
        }
      });
    },
    changePlane(value) {
      this.form.planeId = value;
    },
    changeItem(value) {
      trainItems = [];
      value.forEach(function (data, index) {
        const item = { id: data }
        trainItems.push(item)
      })
    },

    removeTag(value) {
      trainItems.forEach(function (data, index) {
        if (data.id === value) {
          trainItems.splice(index, value)
        }
      })
    },
    getItems() {
      getItemList({ current: 1, size: 100 }).then(res => {
        this.items = res.content
        this.items.sort((a, b) => a.id - b.id)
      }).catch(() => { })
    },
    getPilots() {
      getPilotList().then(res => {
        this.pilots = res.content
      }).catch(() => { })
    },
    getPlanes() {
      getPlaneList().then(res => {
        this.planes = res.content
      }).catch(() => { })
    },
    getNextItemId() {
      if (this.itemIndex === this.crud.data[this.curRowIndex].items.length - 1) {
        return -1
      }
      return this.crud.data[this.curRowIndex].items[++this.itemIndex].id
    },
    showDialog(row, index) {
      this.itemIndex = 0;
      this.curId = row.id
      this.curRowIndex = index
      this.crud.data[index].items.sort((a, b) => a.id - b.id)
      this.curPilot = row.pilot
      this.isMenuVisible = true
    },
    hanldeItemClick(itemId) {
      this.curItemId = itemId
      this.dialogType = DIALOG_TYPES.get(this.curItemId)
      console.log('curId', this.curItemId, this.dialogType);
    },
    handleDialogClose(itemId) {
      this.dialogType = ''
    },
    hanldeMenuDialogClose(itemId) {
      this.curItemId = -1
      this.curId = -1
      this.isMenuVisible = false
    },
    handleDialogCancel(itemId) {
      this.dialogType = ''
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      trainItems = []
      this.itemDatas = []
      const _this = this
      crud.form.items.sort((a, b) => a.id - b.id).forEach(item => {
        _this.itemDatas.push(item.id)
        const data = { id: item.id }
        trainItems.push(data)
      })
    },
    [CRUD.HOOK.beforeToAdd](crud, form) {
      trainItems = []
      this.itemDatas = []

    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getPilots()
      this.getPlanes()
      this.getItems()
    },
    // 提交前做的操作
    [CRUD.HOOK.beforeValidateCU](crud) {
      crud.form.items = trainItems.sort((a, b) => a.id - b.id)
      return true
    }
  }
}
</script>

<style scoped></style>
